// 模板解析
// import {get,has,set} from "lodash-es"
// {{ exp }} 表达式模板 (str,ctx) => string
const REG_EXP2STR = /\{\{\s*(.*?)\s*\}\}/g;

// $0-99 替换模板  (str,arr) => string
const REG_NUM2STR = /\$(\d+)\s*/g;

// # exp (str,ctx) => any   
// {}
// [k,{{exp}},{k:v,{{exp}}:{{exp}},sk },[...]]
// [key1,{{ exp }},[k1,k2],{ks:kt,k=[]},ks:kt] (str,ctx) => source
// {key1,K={{exp}},{{exp}} = v,k=v,K1:k2 = v,k=[k1,k2,k3],k={K:[k2,k3,{{exp}}]}}
// const REG_DATA = /^$/

// [a,b,c] (str,arr) => {a,b,c} 解构赋值
// [a,b,c]|{a,b,c} (str,ctx) => {a,b,c}
// const REG_DESTUCT = /^\s*(\[(.*)\])|({(.*)})\s*$/

// const REG_KEY = /[^\s,;\n\t()\[\]{}+\-*\/\\]/g
// const REG_KEY = /(?:"(.*?)")|(?:'(.*?)')|(?:([\w$]+))/g

export namespace Temp {

    export const exec = (s: string, ctx: any) => {
        const keys = Object.keys(ctx);
        const vals = keys.map(k => ctx[k])
        const str = 'return ' + s;
        return new Function(...keys, str)(...vals)
    }

    export const loop = (s: string, reg: RegExp, call: (r: RegExpExecArray) => void) => {
        let t: RegExpExecArray | null;
        while ((t = reg.exec(s)) !== null) {
            call(t);
        }
    }

    export const exp2str = (str: string, ctx: any) => {
        let r = str;
        loop(str,REG_EXP2STR,(t) => {
            const [s,k] = t;
            const v = exec(k,ctx);
            r = r.replace(s,v);
        })
        return r;
    }

    export const num2str = (str: string, arr: any[]) => {
        let r = str;
        loop(str,REG_NUM2STR,(t) => {
            const [s,k] = t;
            const i = Number(k)
            let v = '';
            if(i >=0 && i < arr.length){
                v = arr[i]
            }
            r = r.replace(s,v);
        })
        return r;
    }

    // export const destruct = (str:string,obj:any,isTrue=false) => {
    //     const isArray = isTrue && /^\[/.test(str)
    //     const t = REG_DESTUCT.exec(str)
    //     const r:any = isArray ? [] : {};
    //     if(t){
    //         const ks = (t[2] || t[4]).split(',');
    //         for(const mk of ks){
    //             const [nk,dv] = mk.trim().split('=')
    //             const [sk,tk] = nk.trim().split(':')
    //             let k = tk ? tk.trim() : sk.trim();
    //             const v = has(obj,sk.trim()) ? get(obj,sk.trim()) : dv;
    //             if(v != undefined){
    //                 isArray? r.push(v) : set(r,k,v)
    //             }
    //         }
    //     }
    //     return r;
    // }
    //

    
}